package ModelLayer;
import java.util.ArrayList;
import java.lang.String;
import java.util.Iterator;
/**
 * Write a description of class LoanContainer here.
 * 
 * @author (your id) 
 * @version (a version number or a date)
 */
public class LoanContainer
{
    private ArrayList<Loan>listOfLoans;
    private static LoanContainer instance;

    /**
     * Constructor for objects of class LoanContainer
     */
    private LoanContainer()
    {
        listOfLoans = new ArrayList<Loan>();   
    }

    public static LoanContainer getInstance()
    {
        if(instance == null)
        {
            instance = new LoanContainer();
        }
        return instance;
    }

    public boolean search(String id)
    {    
        for (Loan loan : listOfLoans)
        {
            if (loan.getId().equals(id)) 
            {
                return true;
            }
        }
        return false; 
    }

    private void addLoan(Loan loan)
    {
        listOfLoans.add(loan);
    }

    public Loan findLoan(String id)
    {
        int index = 0;
        boolean found = false;
        while(index < listOfLoans.size() && !found)
        {
            Loan loan = listOfLoans.get(index);
            if(listOfLoans.get(index).getId().equals(id))
            {
                found = true;
            }
            else
            {
                index++;
            }
        }
        if(found == true)
        {
            return listOfLoans.get(index);
        }
        else
        {
            return null;
        }
    }

    public void deleteLoan(String id)
    {
        Iterator<Loan> it = listOfLoans.iterator();
        while(it.hasNext())
        {
            Loan t = it.next();
            String idToRemove = t.getId();
            if(idToRemove.equals(id))
            {
                it.remove();
            }
        }
    }

    public void createLoan(String id, String borrowDate, String period, String serialNo, String purchaseDate, String purchasePrice, String name, String title)
    {
        if(!search(id))
        {
            Loan l = new Loan(id,borrowDate,period,serialNo, purchaseDate, purchasePrice,name,title);
            listOfLoans.add(l);
        }
        else
        {
            System.out.println("Id already exists.");
        }
    }

    public ArrayList<Loan> getList()
    {
        return listOfLoans;
    }
}
    